package com.study.goal.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.study.common.core.domain.PageQuery;
import com.study.common.core.page.TableDataInfo;
import com.study.common.utils.StringUtils;
import com.study.goal.domain.Goal;
import com.study.goal.domain.Plan;
import com.study.goal.domain.bo.GoalBo;
import com.study.goal.domain.bo.PlanBo;
import com.study.goal.domain.vo.PlanVo;
import com.study.goal.mapper.PlanMapper;
import com.study.goal.service.IPlanService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Date;

@RequiredArgsConstructor
@Service
public class IPlanServiceImpl implements IPlanService {

    private final PlanMapper planMapper;

    @Override
    public PlanVo queryById(Long id) {
        return planMapper.selectVoById(id);
    }

    @Override
    public TableDataInfo<PlanVo> queryPageList(PlanBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Plan> lqw = buildQueryWrapper(bo);
        Page<PlanVo> result = planMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<PlanVo> queryPageListById(Long goalId, PageQuery pageQuery) {
        LambdaQueryWrapper<Plan> lqw = Wrappers.lambdaQuery();
        lqw.eq(goalId != null, Plan::getGoalId, goalId);
        Page<PlanVo> result = planMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public Boolean insertByBo(PlanBo bo) {
        Plan plan = BeanUtil.toBean(bo, Plan.class);
        plan.setPlanCode(IdUtil.simpleUUID());
        plan.setCreateTime(LocalDate.now());
        return planMapper.insert(plan) > 0;
    }

    @Override
    public Boolean updateByBo(PlanBo bo) {
        return planMapper.updateById(BeanUtil.toBean(bo, Plan.class)) > 0;
    }

    @Override
    public Boolean deleteWithValidById(Long id, Boolean isValid) {
        return planMapper.deleteById(id) > 0;
    }


    private LambdaQueryWrapper<Plan> buildQueryWrapper(PlanBo bo) {
        LambdaQueryWrapper<Plan> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getGoalId() != null, Plan::getGoalId, bo.getGoalId());
        lqw.eq(bo.getPlanCode() != null, Plan::getPlanCode, bo.getPlanCode());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), Plan::getStatus, bo.getStatus());
        return lqw;
    }
}
